package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    // 查询今日佳人
    @Override
    public RecommendUser findMaxScoreRecommendUser(Long userId) {
        // 1.构建查询对象
        Query query = new Query(
                Criteria.where("toUserId").is(userId)
        ).with(Sort.by(Sort.Order.desc("score")))
                .skip(0).limit(1);

        // 2.查询
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        // 3.返回
        return recommendUser;
    }

    // 查询推荐用户列表
    @Override
    public PageBeanVo findRecommendUserByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 1.构建查询对象
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query(
                Criteria.where("toUserId").is(userId)
        ).with(Sort.by(Sort.Order.desc("score")))
                .skip(index + 1).limit(pageSize);// 排除今日佳人

        // 2.查询list
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);

        // 3.查询总记录数
        long count = mongoTemplate.count(query, RecommendUser.class);

        // 4.返回分页对象
        return new PageBeanVo(pageNum, pageSize, count, recommendUserList);
    }

    // 查询推荐用户详情
    @Override
    public RecommendUser findRecommendUserById(Long recommendUserId, Long userId) {
        // 1.构建查询条件
        Query query = new Query(
                Criteria.where("userId").is(recommendUserId)
                        .and("toUserId").is(userId));

        // 2.查询recommendUser
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        // 3.返回
        return recommendUser;
    }
}
